package com.tang.utils;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.fastjson.JSONObject;
import com.tang.system.entity.SysUser;
import lombok.Getter;
import lombok.Setter;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

public class LoginUtils {
    public static String createLoginToken(SysUser sysUser) {
        Map<String, Object> map = createTokenUserInfo(sysUser);
        String token = JWTUtil.createToken(map, sysUser.getSalt().getBytes(StandardCharsets.UTF_8));
        token = sysUser.getUsername() + "$$" + token;
        return token;
    }

    private static Map<String, Object> createTokenUserInfo(SysUser sysUser) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Random random = new Random();
        TokenUserInfo info = new TokenUserInfo();
        info.setUsername(sysUser.getUsername());
        info.setTimestamp(simpleDateFormat.format(new Date()));
        info.setRandom(random.nextInt(random.nextInt(1000)));
        return JSONObject.parseObject(JSONObject.toJSONString(info)).getInnerMap();
    }

    public static String createPassword(String username, String password, String salt) {
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        String str = username + "|" + password + "|" + salt + "|asdfasdf|asdfweffgsfghs";
        return md5.digestHex(str, StandardCharsets.UTF_8);
    }

    public static boolean checkPassWord(String password, SysUser sysUser) {
        String password1 = sysUser.getPassword();
        String password2 = createPassword(sysUser.getUsername(), password, sysUser.getSalt());

        return password1.equals(password2);
    }

    public static void main(String[] args) {
        System.out.println(createPassword("tangzy", "123456", "tangzy"));;
        System.out.println(createPassword("admin", "123456", "admin"));;
    }

    @Getter
    @Setter
    static class TokenUserInfo {
        private String username;
        private String timestamp;
        private Integer random;
    }
}
